package com.erbadagang.springcloud.gateway.sentinel.handler;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description 自定义的限流返回信息。
 * @ClassName: CustomBlockRequestHandler
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/7/31 11:21
 * @Copyright:
 */
@Component
public class CustomBlockRequestHandler implements BlockRequestHandler {

    private static final String DEFAULT_BLOCK_MSG_PREFIX = "This request is blocked by guoxiuzhi's sentinel.";

    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
        String bodyJson = "{\n" +
                "  \"code\": 429,\n" +
                "  \"data\": \"%s The detail exception class: %s \"\n" +
                "}";

        return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS) // 状态码
                .contentType(MediaType.TEXT_PLAIN) // 内容类型为 text/plain 纯文本
                .bodyValue(String.format(bodyJson, DEFAULT_BLOCK_MSG_PREFIX, ex.getClass().getSimpleName())); // 错误提示
    }

}
